package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.rest.entity.RestDict;
import cn.stylefeng.guns.sys.modular.system.db6.entity.SysDict;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyPerformanceMonthCheckMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyPerformanceMonthInformationMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyPerformancePointMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyPerformanceMonthCheckParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyPerformanceMonthInformationParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyPerformanceMonthPermissionsParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyPerformanceReceiveParam;
import cn.stylefeng.guns.sys.modular.system.model.result.*;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dianping.orderdish.openplatform.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wjk
 * @since 2022-02-10
 */
@Service
public class BtyPerformanceMonthCheckServiceImpl extends ServiceImpl<BtyPerformanceMonthCheckMapper, BtyPerformanceMonthCheck> implements BtyPerformanceMonthCheckService {

    /**
     * 这是yingye的人员档案信息类
     */
    @Autowired
    private AttendAuditBtyArchivesService attendAuditBtyArchivesService;

    /**
     * 这是yingye的督导指定店长的服务类
     */
    @Autowired
    private AttendAuditBtyAreaService attendAuditBtyAreaService;

    //获取做绩效的配置信息表
    @Autowired
    private BtyPerformanceMonthConfigService btyPerformanceMonthConfigService;

    //绩效点数配置表
    @Autowired
    private BtyPerformancePointService btyPerformancePointService;

    //月度绩效详情
    @Autowired
    private BtyPerformanceMonthInformationService btyPerformanceMonthInformationService;
    @Autowired
    private BtyPerformancePointMapper performancePointMapper;
    @Autowired
    BtyPerformanceMonthInformationMapper btyPerformanceMonthInformationMapper;

    @Override
    public void add(BtyPerformanceMonthCheckParam param){
        BtyPerformanceMonthCheck entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyPerformanceMonthCheckParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyPerformanceMonthCheckParam param){
        BtyPerformanceMonthCheck oldEntity = getOldEntity(param);
        BtyPerformanceMonthCheck newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyPerformanceMonthCheckResult findBySpec(BtyPerformanceMonthCheckParam param){
        return null;
    }

    @Override
    public List<BtyPerformanceMonthCheckResult> findListBySpec(BtyPerformanceMonthCheckParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyPerformanceMonthCheckParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 根据用户手机号，和店面的妖码，还有当前时间，验证当前用户是否有操作此店本月绩效的权限
     *
     * @author wjk
     * @Date 2021-02-17
     * @param param
     * @return map
     * permissionsValid = true 则证明是有权限操作的，
     * permissionsValid = false 时给出原因
     * permissionsInfo 权限信息说明
     *
     */
    @Override
    public Map<String, String> BtyPerformanceMonthPermissionsValidation(BtyPerformanceMonthPermissionsParam param) {

        Map<String, String> map = new HashMap<String, String>();
        // 判断是否在绩效创建时间
        Map<String,String> mapTime = getPerformanceDay();
        if("1".equals(mapTime.get("pageValid"))){
            map.put("permissionsValid","false");
            map.put("permissionsInfo","不是在绩效提交时间内，不允许编辑或提交绩效信息。"+mapTime.get("pageInfo"));
            return map;
        }

        // 获取此用户的权限，是否允许创建
        Map<String,String> mapIdentity = checkIdentity(param.getAccount());
        if("1".equals(mapIdentity.get("permissionsValid"))){
            map.put("permissionsValid","false");
            map.put("permissionsInfo","当前登录用户，没有绩效编辑或提交权限，若需要请联系人事同事修改用户职位。"+mapIdentity.get("permissionsInfo"));
            return map;
        }

        // 根据妖码，和时间，查询这个店的信息
        BtyPerformanceReceiveParam btyPerformanceReceiveParam = new BtyPerformanceReceiveParam();
        btyPerformanceReceiveParam.setYaoma(param.getYaoma());
        btyPerformanceReceiveParam.setTime(mapTime.get("lastYearMonth"));
        BtyDdpageByAccountTime btyDdpageByAccountTime = getBtyDdpageByYaomaTime(btyPerformanceReceiveParam);

        if(ToolUtil.isEmpty(btyDdpageByAccountTime)||ToolUtil.isEmpty(btyDdpageByAccountTime.getId())){
            map.put("permissionsValid","false");
            map.put("permissionsInfo","根据未查询到此店信息，请确认此店是否在人事档案数据中建店。");
            return map;
        }
        //  判断此用户是否有此店的权限
        // 默认没有该店的权限
        Boolean flagNotHaveShopIdentity = true ;
        if(ToolUtil.isNotEmpty(mapIdentity.get("userZwAllStr"))){
            if(mapIdentity.get("userZwAllStr").indexOf("督导")>-1&&ToolUtil.isNotEmpty(btyDdpageByAccountTime.getDddh())&&btyDdpageByAccountTime.getDddh().equals(param.getAccount())){
                flagNotHaveShopIdentity = false;
            }
            if(mapIdentity.get("userZwAllStr").indexOf("大店长")>-1&&ToolUtil.isNotEmpty(btyDdpageByAccountTime.getDh())&&btyDdpageByAccountTime.getDh().equals(param.getAccount())){
                flagNotHaveShopIdentity = false;
            }
        }
        // 若没有本店权限，返回空
        if(flagNotHaveShopIdentity){
            map.put("permissionsValid","false");
            map.put("permissionsInfo","当前登录用户没有创建或者编辑该店绩效的权限，请确认后操作。");
            return map;
        }

        map.put("permissionsValid","true");
        map.put("permissionsInfo","权限验证通过，可进行创建或者编辑该店人员绩效。");
        return map;
    }






    /**
     * 根据审核id 查询提交的信息，查询上个月，合计的绩效点数
     * @param param
     * @return
     */
    private BtyPerformanceMonthCheck queryBtyPerformanceMonthCheckByCheckIdAndYaoma(BtyPerformanceMonthInformationParam param) {

        LambdaQueryWrapper<BtyPerformanceMonthCheck> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BtyPerformanceMonthCheck::getId,param.getBtyPerformanceMonthCheckId());
        queryWrapper.eq(BtyPerformanceMonthCheck::getYaoma,param.getYaoma());
        List<BtyPerformanceMonthCheck> list = this.list(queryWrapper);
        if(list.size()>0){
            return list.get(0);
        }
        return new BtyPerformanceMonthCheck();

    }

    /**
     * 后台-当前登陆者身份判断,是否有权限进入创建绩效页面；
     * @author wjk
     * @Date 2021-09-15
     */
    @Override
    public Map<String, String> checkIdentity(String account) {
        Map<String,String> map = new HashMap<String, String>();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        map.put("time",sdf.format(date));

        map.put("permissionsValid","1");
        map.put("userZwAllStr","");
        map.put("permissionsZw","");

        //判断该用户是否已经在人事表中有数据
        AttendAuditBtyArchives attendAuditBtyArchives = attendAuditBtyArchivesService.getOneByPhone(account);

        //判断该用户在架构中，是否有，营运经理，督导，大店长，店长，职位
        String zwStr = attendAuditBtyAreaService.getBtyAreaZwByTel(account);
        map.put("userZwAllStr",zwStr);
        //查找可以进行做绩效的职位
        List<BtyPerformanceMonthConfig> list = btyPerformanceMonthConfigService.getOperation();
        if(list.size() == 0){
            map.put("permissionsInfo","当前时间没有可以做绩效的职位，请联系管理员新增权限。");
            return map;
        }

        //匹配做绩效的职位，若有返回权限，证明可以进入页面中
        if(list.size() > 0){
            String[] nameArray = new String[list.size()];
            for(int i = 0; i<list.size(); i++){
                nameArray[i] = list.get(i).getName();
                if(zwStr.indexOf(list.get(i).getName())>-1){
                    map.put("permissionsValid","0");
                }
            }
            map.put("permissionsZw", StringUtils.join(nameArray, ","));
        }
        if(map.get("permissionsValid").equals("0")){
            map.put("permissionsInfo","当前用户有做绩效的权限,当前用户在营运架构中的角色为["+zwStr+"],允许做绩效的角色为["+map.get("permissionsZw")+"]。");
        }

        if(map.get("permissionsValid").equals("1")){
//            map.put("permissionsInfo","当前用户没有做绩效的权限,当前用户在营运架构中的角色为["+zwStr+"],允许做绩效的角色为["+map.get("permissionsZw")+"]。");
            map.put("permissionsInfo","只允许[" + map.get("permissionsZw") + "]做绩效，您暂无权限。");
        }
        return map;
    }

    /**
     * 判断当前时间，是否是在做绩效的时间，若之前,则提示；若之后则查询
     * @author wjk
     * @Date 2021-02-11
     */
    @Override
    public Map<String, String> getPerformanceDay() {

        Map<String, String> map = new HashMap<String, String>();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        map.put("time",sdf.format(date));
        //默认当前不允许做绩效
        map.put("pageValid","1");
        map.put("pageInfo","");
        map.put("performanceDay","");

        //做绩效的月份，默认是上个月
        Map<String, String> mapLastMonth = btyPerformancePointService.getAttendMonth();
        map.put("performanceMonth",mapLastMonth.get("lastMonth"));
        map.put("lastYearMonth",mapLastMonth.get("lastYearMonth"));

        SimpleDateFormat daySdf = new SimpleDateFormat("dd");
        String day = daySdf.format(date);

        List<RestDict> listRestDict = btyPerformanceMonthConfigService.getPerformanceDay();

        if(listRestDict.size() == 0){
            map.put("pageInfo","未设置做绩效提交的时间，请联系管理员新增允许绩效提交时间。");
            return map;
        }
        //匹配当前时间是否是允许做考勤的时间，若是在绩效提交时间则返回，可以查询时间
        if(listRestDict.size() > 0){

            String[] nameArray = new String[listRestDict.size()];
            for(int i = 0;i<listRestDict.size();i++){
                nameArray[i] = listRestDict.get(i).getCode();
                if(listRestDict.get(i).getCode().equals(day)){
                    // 允许创建上个月绩效
                    map.put("pageValid","0");
                }
            }

            map.put("performanceDay", StringUtils.join(nameArray, ","));
        }

        if(map.get("pageValid").equals("0")){
            map.put("pageInfo"," 当前时间允许绩效提交, 每月["+ map.get("performanceDay")+"]允许绩效提交。");
        }

        if(map.get("pageValid").equals("1")){
            map.put("pageInfo","还未到做绩效时间, 请在每月["+ map.get("performanceDay")+"]号做绩效提交。");
        }
        return map;
    }

    /**
     * 5.待提交，已提交，督导(或大店长)下属店，统计店的个数信息
     * @author wjk
     * @Date 2021-02-14
     */

    @Override
    public Map<String, String> getShopListSumByPhone(String account, BtyPerformanceReceiveParam param) {

        Map<String, String> map = new HashMap<String, String>();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        map.put("time",sdf.format(date));
        //默认当前不允许做绩效
        map.put("submitSum","");
        map.put("notSubmitSum","");
        // 根据手机号判断用户角色
        Map<String,String> mapUser = checkIdentity(account);
        map.put("userZwAllStr",mapUser.get("userZwAllStr"));
        // 判断考勤月份
        if (ObjectUtil.isEmpty(param.getTime())) {
            Map<String,String> mapTime = getPerformanceDay();
            param.setTime(mapTime.get("lastYearMonth"));
        }
        map.put("lastYearMonth",param.getTime());

        //查询未提交的店的个数
        param.setCheckStatus("0");
        LayuiPageInfo pageInfoNotSubmitSum = btyPerformancePointService.findPageByAccountTime(account,param);

        map.put("notSubmitSum",String.valueOf(pageInfoNotSubmitSum.getCount()));

        //查询已提交的店的个数
        param.setCheckStatus("1");
        LayuiPageInfo pageInfoSubmitSum = btyPerformancePointService.findPageByAccountTime(account,param);

        map.put("submitSum",String.valueOf(pageInfoSubmitSum.getCount()));
        return map;
    }




    /**
     * 6.待提交的店，点击编辑，判断是否已经创建了该店，本月的绩效信息，若已经创建，则直接进入，返回本店上月的绩效人员信息，若未创建，则创建本店上月绩效信息
     * @author wjk
     * @Date 2021-02-14
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> setEmployeeListByYaoma(String account, BtyPerformanceReceiveParam param) {
        Map<String, Object> map = new HashMap<String, Object>();

        // 根据用户手机号，和店面的妖码，还有当前时间，验证当前用户是否有操作此店本月绩效的权限
        BtyPerformanceMonthPermissionsParam permissionsParam = new BtyPerformanceMonthPermissionsParam();
        permissionsParam.setAccount(account);
        permissionsParam.setYaoma(param.getYaoma());

        Map<String,String> mapPermissions = this.BtyPerformanceMonthPermissionsValidation(permissionsParam);
        if(mapPermissions.get("permissionsValid").equals("false")){
            map.put("flag","false");
            map.put("message",mapPermissions.get("permissionsInfo"));
            map.put("data","");
            return map;
        }

        // 根据妖码，和时间，查询这个店的信息
        Map<String,String> mapTime = getPerformanceDay();
        param.setTime(mapTime.get("lastYearMonth"));

        BtyDdpageByAccountTime btyDdpageByAccountTime = getBtyDdpageByYaomaTime(param);

        //判断纯利大于0才可以继续创建
        if(ToolUtil.isEmpty(btyDdpageByAccountTime.getCl())){
            map.put("flag","false");
            map.put("message","此店在["+param.getTime()+"]月，未查询到纯利,请确认此店是否为新店，或者已经闭店，若不是新店并且没有闭店，请督导联系人事同步此店上月度纯利信息。");
            map.put("data","");
            return map;
        }
        if(ToolUtil.isNotEmpty(btyDdpageByAccountTime.getCl())){
            BigDecimal num = btyDdpageByAccountTime.getCl();
            int i = num.compareTo(BigDecimal.ZERO);
            if(i == -1){
                map.put("flag","false");
                // map.put("message","此店在["+param.getTime()+"]月，纯利小于零，无需创建绩效提交信息。");
                //XXX纯利为0，无法做绩效
                map.put("message","[" + btyDdpageByAccountTime.getDm() + "]纯利为" + btyDdpageByAccountTime.getCl() + "，无法做绩效");
                map.put("data","");
                return map;
            }
            if( i == 0){
                map.put("flag","false");
                // map.put("message","此店在["+param.getTime()+"]月，纯利等于零，无需创建绩效提交信息。");
                map.put("message","[" + btyDdpageByAccountTime.getDm() + "]纯利为0" + "，无法做绩效");
                map.put("data","");
                return map;
            }
            if( i == 1){
                // i大于0 的
            }
        }

        // 判断此店是否创建过，若创建过，返回
        if(ToolUtil.isNotEmpty(btyDdpageByAccountTime.getBtyPerformanceMonthCheckId())){
            //根据 CheckId 获取上月度绩效详情信息;
            List<BtyPerformanceMonthInformation> list = btyPerformanceMonthInformationService.getBtyPerformanceMonthInformationListPageByCheckId(btyDdpageByAccountTime.getBtyPerformanceMonthCheckId());
            map.put("flag","true");
            map.put("message","查询成功。");
            map.put("data",list);
            return map;
        }
        // 判断此店，没有创建过，创建此店的绩效提交信息
        if(ToolUtil.isEmpty(btyDdpageByAccountTime.getBtyPerformanceMonthCheckId())){
            //根据妖码信息创建上月的月度绩效审核数据；
            BtyPerformanceMonthCheck btyPerformanceMonthCheck = createCheckByYaoma(account, param);
            //根据 CheckId 获取 月度绩效详情信息;
            List<BtyPerformanceMonthInformation> list = btyPerformanceMonthInformationService.getBtyPerformanceMonthInformationListPageByCheckId(btyPerformanceMonthCheck.getId());
            map.put("flag","true");
            map.put("message","查询成功。");
            map.put("data",list);
            return map;
        }

        return map;
    }

    /**
     * 根据妖码信息创建上月的月度绩效审核数据；
     *
     * @author wjk
     * @Date 2021-02-14
     */
    @Transactional(rollbackFor = Exception.class)
    public BtyPerformanceMonthCheck createCheckByYaoma(String account, BtyPerformanceReceiveParam param) {
        BtyDdpageByAccountTime btyDdpageByAccountTime = getBtyDdpageByYaomaTime(param);

        BtyPerformanceMonthCheck entity =  new BtyPerformanceMonthCheck();
        Long id = Long.valueOf(param.getTime()+btyDdpageByAccountTime.getYaoma());
        // id
        entity.setId(id);
        entity.setMonth(param.getTime());
        entity.setDm(btyDdpageByAccountTime.getDm());
        entity.setYaoma(btyDdpageByAccountTime.getYaoma());
        entity.setCheckStatus(0);
        entity.setJb(btyDdpageByAccountTime.getJb());
        entity.setMangerRatio(btyDdpageByAccountTime.getMangerRatio());
        entity.setCreateTime(new Date());
        entity.setCreateUser(Long.valueOf(account));
        Boolean flag = this.save(entity);
        if(flag){
            //根据店名，查询上个月的考勤信息
            List<BtyPerformanceMonthInformation> list = this.btyPerformanceMonthInformationService.getBtyPerformanceMonthInformation(param);
            if(list.size()>0){
                for(BtyPerformanceMonthInformation item:list){
                    Long BtyPerformanceMonthInformationId = UUIDUtils.getId();
                    item.setId(BtyPerformanceMonthInformationId);
                    item.setBtyPerformanceMonthCheckId(entity.getId());
                    item.setCreateTime(new Date());
                    item.setCreateUser(Long.valueOf(account));
                    //Boolean one  = this.btyPerformanceMonthInformationService.save(item);
                }
            }
            //Boolean flagBtyPerformanceMonthInformationList = this.btyPerformanceMonthInformationService.saveBatch(list);
            // 批量保存
            int saveSize = this.btyPerformanceMonthInformationService.saveList(list);
        }

        return entity;
    }

    /**
     * 根据妖码,月份，查询这个店的信息
     *
     * @author wjk
     * @Date 2021-02-14
     */
    @Override
    public BtyDdpageByAccountTime getBtyDdpageByYaomaTime(BtyPerformanceReceiveParam param) {

         List<BtyDdpageByAccountTime> list =  this.baseMapper.getBtyDdpageByYaoma(param);
         if(list.size()>0){
             return list.get(0);
         }
         return new BtyDdpageByAccountTime();
    }


    /**
     * 9.点击新增人员，查询相同运营经理下的店的店内的店长，店助，运营经理，督导等的职位信息
     * @author wjk
     * @Date 2021-02-15
     */
    @Override
    public LayuiPageInfo getBtyArchives(String account, BtyPerformanceReceiveParam param) {

        // 获取此用户的权限，是否允许创建
        Map<String,String> mapIdentity = checkIdentity(account);
        if("1".equals(mapIdentity.get("permissionsValid"))){
            new LayuiPageInfo();
        }

        //根据当前登录人手机号，查询此人所在店的运营经理

        List<AttendAuditBtyArea> attendAuditBtyAreaList = new ArrayList<AttendAuditBtyArea>();

        if(mapIdentity.get("userZwAllStr").indexOf("大店长")>-1){
            attendAuditBtyAreaList = this.attendAuditBtyAreaService.getShowListByDdzTel(account,null);
        }

        if(mapIdentity.get("userZwAllStr").indexOf("督导")>-1){
            attendAuditBtyAreaList = this.attendAuditBtyAreaService.getShowListByDdTel(account,null);
        }

        if(attendAuditBtyAreaList.size() == 0){
            new LayuiPageInfo();
        }

        //根据营运经理电话，查询营运经理所有的店的
        String yydh = "";
        if(attendAuditBtyAreaList.size() > 0){
            yydh = attendAuditBtyAreaList.get(0).getYydh();
        }

        //此处先注解掉不确认后期会不会加数据；
        //查询运营经理的店，根据运营经理电话；
        //List<AttendAuditBtyArea> attendAuditBtyAreaListYYjl = this.attendAuditBtyAreaService.getShowListByYyjlTel(yydh,null);

        // 查询可以被做绩效的职位
        //查找可以进行做绩效的职位
        List<BtyPerformanceMonthConfig> performanceList = btyPerformanceMonthConfigService.getPerformance();
        if(performanceList.size() == 0){
            new LayuiPageInfo();
        }

        // 根据店的列表查询,和做绩效的职位查询用户信息;
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getBtyArchives(pageContext, param, yydh,performanceList);
        return LayuiPageFactory.createPageInfo(page);
    }


    /**
     * 11.点击提交上月绩效信息，判断点数相加<=总点数
     * @author wjk
     * @Date 2021-02-15
     */
    @Override
    public Map<String, String> submitPerformanceMonthCheck(String account, BtyPerformanceMonthInformationParam param) {
        Map<String, String> map = new HashMap<>();

        // 根据用户手机号，和店面的妖码，还有当前时间，验证当前用户是否有操作此店本月绩效的权限
        BtyPerformanceMonthPermissionsParam permissionsParam = new BtyPerformanceMonthPermissionsParam();
        permissionsParam.setAccount(account);
        permissionsParam.setYaoma(param.getYaoma());

        Map<String,String> mapPermissions = this.BtyPerformanceMonthPermissionsValidation(permissionsParam);
        if(mapPermissions.get("permissionsValid").equals("false")){
            map.put("flag","false");
            map.put("message",mapPermissions.get("permissionsInfo"));
            map.put("data","");
            return map;
        }

        // 根据审核id 妖码提交的信息，店的绩效点数
        BtyPerformanceMonthCheck btyPerformanceMonthCheck = queryBtyPerformanceMonthCheckByCheckIdAndYaoma(param);
        if(ToolUtil.isEmpty(btyPerformanceMonthCheck)||ToolUtil.isEmpty(btyPerformanceMonthCheck.getId())){
            map.put("flag","false");
            map.put("message","未查询到审核信息！");
            map.put("data","");
            return map;
        }

        BigDecimal allRatio = BigDecimal.ZERO;

        List nameList =new ArrayList();
        // 根据审核id 查询提交的信息，查询上个月，合计的绩效点数
        List<BtyPerformanceMonthInformation> list = this.btyPerformanceMonthInformationService.getBtyPerformanceMonthInformationListPageByCheckId(param.getBtyPerformanceMonthCheckId());
        if(list.size() > 0){
            for(BtyPerformanceMonthInformation item:list){
                allRatio =  allRatio.add(item.getRatio());
                //添加的人员中有占比为空或者为0的
                if(ObjectUtil.isEmpty(item.getRatio())||item.getRatio().compareTo(BigDecimal.ZERO)==0){
                    nameList.add(item.getXm());
                }

            }

            //根据审核表id,查询提交的绩效信息，判断绩效占比为空为0需提示【占比不能为空，请填写xxx的占比】
            if(nameList.size()>0){
                map.put("flag","false");
                map.put("message","绩效占比不能为空，请填写"+nameList+"的占比");
                map.put("data","");
                return map;
            }

        }

//        A.compareTo(B)>0 ，即使A>B
//        A.compareTo(B)=0 ，即使A=B
//        A.compareTo(B)<0 ，即使A<B
        // 根据绩效点数，对比，若小于等于店的绩效点数，则，不用继续在
        if(allRatio.compareTo(btyPerformanceMonthCheck.getMangerRatio())>0){
            map.put("flag","false");
            // map.put("message","此店人员绩效点数合计"+allRatio+"，此店"+btyPerformanceMonthCheck.getMonth()+"月份绩效评级为"+btyPerformanceMonthCheck.getJb()+",最大允许绩效点数和为"+btyPerformanceMonthCheck.getMangerRatio()+"。");
            //%.2f %. 表示 小数点前任意位数   2 表示两位小数 格式后的结果为f 表示浮点型
            String mangerRatioStr = String.format("%.2f", btyPerformanceMonthCheck.getMangerRatio());
            map.put("message","本店总占比为"+mangerRatioStr+"%,不得超过总占比。");
            map.put("data","");
            return map;
        }
        //根据审核表id,查询提交的绩效信息，判断绩效占比为空为0需提示【占比不能为空或为0，请填写xxx的占比】


        btyPerformanceMonthCheck.setCheckStatus(1);
        btyPerformanceMonthCheck.setUpdateTime(new Date());
        btyPerformanceMonthCheck.setUpdateUser(Long.valueOf(account));
        boolean flag = this.updateById(btyPerformanceMonthCheck);
        // 将此单的所有驳回状态修改为历史记录
        boolean flagDismissed = this.baseMapper.updateDismissedHistorytryById(btyPerformanceMonthCheck.getId());

        if(flag){
            map.put("flag","true");
            map.put("message"," 提交成功。");
            map.put("data","");
            return map;
        }
        map.put("flag","false");
        map.put("message","提交失败。");
        map.put("data","");
        return map;

    }

    /**
     * 12.已提交，点击查看，查询店内人员的状态信息
     * @author wjk
     * @Date 2021-02-16
     */
    @Override
    public Map<String, Object> queryPerformanceMonthCheckById(String account, BtyPerformanceMonthInformationParam param) {
        Map<String, Object> map = new HashMap<>();

//        // 根据用户手机号，和店面的妖码，还有当前时间，验证当前用户是否有操作此店本月绩效的权限
//        BtyPerformanceMonthPermissionsParam permissionsParam = new BtyPerformanceMonthPermissionsParam();
//        permissionsParam.setAccount(account);
//        permissionsParam.setYaoma(param.getYaoma());
//
//        Map<String,String> mapPermissions = this.BtyPerformanceMonthPermissionsValidation(permissionsParam);
//        if(mapPermissions.get("permissionsValid").equals("false")){
//            map.put("flag","false");
//            map.put("message",mapPermissions.get("permissionsInfo"));
//            map.put("data","");
//            return map;
//        }

        //  判断此用户是否有此店的权限
        // 判断是否在绩效创建时间
        Map<String,String> mapTime = getPerformanceDay();

        // 根据妖码，和时间，查询这个店的信息
        BtyPerformanceReceiveParam btyPerformanceReceiveParam = new BtyPerformanceReceiveParam();
        btyPerformanceReceiveParam.setYaoma(param.getYaoma());
        btyPerformanceReceiveParam.setTime(mapTime.get("lastYearMonth"));
        BtyDdpageByAccountTime btyDdpageByAccountTime = getBtyDdpageByYaomaTime(btyPerformanceReceiveParam);


        // 获取此用户的权限，是否允许创建
        Map<String,String> mapIdentity = checkIdentity(account);
        // 默认没有该店的权限
        Boolean flagNotHaveShopIdentity = true ;
        if(ToolUtil.isNotEmpty(mapIdentity.get("userZwAllStr"))){
            if(mapIdentity.get("userZwAllStr").indexOf("督导")>-1&&ToolUtil.isNotEmpty(btyDdpageByAccountTime.getDddh())&&btyDdpageByAccountTime.getDddh().equals(account)){
                flagNotHaveShopIdentity = false;
            }

            if(mapIdentity.get("userZwAllStr").indexOf("大店长")>-1&&ToolUtil.isNotEmpty(btyDdpageByAccountTime.getDh())&&btyDdpageByAccountTime.getDh().equals(account)){
                flagNotHaveShopIdentity = false;
            }

            if(mapIdentity.get("userZwAllStr").indexOf("营运经理")>-1&&ToolUtil.isNotEmpty(btyDdpageByAccountTime.getYydh())&&btyDdpageByAccountTime.getYydh().equals(account)){
                flagNotHaveShopIdentity = false;
            }
        }
        // 若没有本店权限，返回空
        if(flagNotHaveShopIdentity){
            map.put("permissionsValid","false");
            map.put("permissionsInfo","当前登录用户没有创建或者编辑该店绩效的权限，请确认后操作。");
            return map;
        }

        // 根据审核id 妖码提交的信息，店的绩效点数
        BtyPerformanceMonthCheck btyPerformanceMonthCheck = queryBtyPerformanceMonthCheckByCheckIdAndYaoma(param);
        if(ToolUtil.isEmpty(btyPerformanceMonthCheck)||ToolUtil.isEmpty(btyPerformanceMonthCheck.getId())){
            map.put("flag","false");
            map.put("message","未查询到审核信息！");
            map.put("data","");
            return map;
        }
        // 判断状态，若为待提交或者被驳回，则提示不允许查看
        if(!String.valueOf(btyPerformanceMonthCheck.getCheckStatus()).equals("1")){
            map.put("flag","false");
            map.put("message","该店绩效状态为待提交或者被驳回，暂时无法查看。");
            map.put("data","");
            return map;
        }

        List<BtyPerformanceMonthInformation> list = this.btyPerformanceMonthInformationService.getBtyPerformanceMonthInformationListPageByCheckId(param.getBtyPerformanceMonthCheckId());

        map.put("flag","true");
        map.put("message","查询成功！");
        map.put("data",list);

        return map;

    }
    /**
     * 18 运营经理查询待审核店面详情列表，查询提交的绩效详情信息，包含最后一次的驳回原因
     *
     * @author wjk
     * @Date 2022-04-06
     */
    @Override
    public Map<String, Object> queryPerformanceMonthCheckAndDismissedById(String account, BtyPerformanceMonthInformationParam param) {
        Map<String, Object> map = new HashMap<>();

        //  判断此用户是否有此店的权限
        // 判断是否在绩效创建时间
        Map<String,String> mapTime = getPerformanceDay();

        // 根据妖码，和时间，查询这个店的信息
        BtyPerformanceReceiveParam btyPerformanceReceiveParam = new BtyPerformanceReceiveParam();
        btyPerformanceReceiveParam.setYaoma(param.getYaoma());
        btyPerformanceReceiveParam.setTime(mapTime.get("lastYearMonth"));
        BtyDdpageByAccountTime btyDdpageByAccountTime = getBtyDdpageByYaomaTime(btyPerformanceReceiveParam);


        // 获取此用户的权限，是否允许创建
        Map<String,String> mapIdentity = checkIdentity(account);
        // 默认没有该店的权限
        Boolean flagNotHaveShopIdentity = true ;
        if(ToolUtil.isNotEmpty(mapIdentity.get("userZwAllStr"))){
            if(mapIdentity.get("userZwAllStr").indexOf("督导")>-1&&ToolUtil.isNotEmpty(btyDdpageByAccountTime.getDddh())&&btyDdpageByAccountTime.getDddh().equals(account)){
                flagNotHaveShopIdentity = false;
            }

            if(mapIdentity.get("userZwAllStr").indexOf("大店长")>-1&&ToolUtil.isNotEmpty(btyDdpageByAccountTime.getDh())&&btyDdpageByAccountTime.getDh().equals(account)){
                flagNotHaveShopIdentity = false;
            }

            if(mapIdentity.get("userZwAllStr").indexOf("营运经理")>-1&&ToolUtil.isNotEmpty(btyDdpageByAccountTime.getYydh())&&btyDdpageByAccountTime.getYydh().equals(account)){
                flagNotHaveShopIdentity = false;
            }
        }
        // 若没有本店权限，返回空
        if(flagNotHaveShopIdentity){
            map.put("flag","false");
            map.put("message","当前登录用户没有创建或者编辑该店绩效的权限，请确认后操作。");
            map.put("data","");
            return map;
        }

        // 根据审核id 妖码提交的信息，店的绩效点数
        BtyPerformanceMonthCheck btyPerformanceMonthCheck = queryBtyPerformanceMonthCheckByCheckIdAndYaoma(param);
        if(ToolUtil.isEmpty(btyPerformanceMonthCheck)||ToolUtil.isEmpty(btyPerformanceMonthCheck.getId())){
            map.put("flag","false");
            map.put("message","未查询到审核信息！");
            map.put("data","");
            return map;
        }
//        // 判断状态，若为待提交或者被驳回，则提示不允许查看
//        if(!String.valueOf(btyPerformanceMonthCheck.getCheckStatus()).equals("1")){
//            map.put("flag","false");
//            map.put("message","该店绩效状态为待提交或者被驳回，暂时无法查看。");
//            map.put("data","");
//            return map;
//        }

        List<BtyPerformanceMonthInformationResult> list = this.btyPerformanceMonthInformationService.getBtyPerformanceMonthInformationListDismissedByCheckId(param.getBtyPerformanceMonthCheckId());

        map.put("flag","true");
        map.put("message","查询成功！");
        map.put("data",list);

        return map;

    }

    /**
     * 查询当前登录督导，或者大店长，门店总数，和可做绩效的门店数量
     * @param account
     * @return
     */
    @Override
    public ResponseData tddgetShopSumMonth(String account, String time) {

        if (ToolUtil.isEmpty(time)){
            Map<String,String> mapTime = getPerformanceDay();
            time = mapTime.get("lastYearMonth");
        }
        Map<String, Integer> map = new HashMap<>();
        //判断该用户在架构中，是否有，营运经理，督导，大店长，店长，职位
        String zwStr = attendAuditBtyAreaService.getBtyAreaZwByTel(account);
        if (zwStr.contains("督导")){
            int conAll = performancePointMapper.ddAllCon(account,time, null);//门店总数
            int con = performancePointMapper.ddCon(account,time);//可做绩效门店数
            map.put("conAll", conAll);
            map.put("con", con);
        }

        if (zwStr.contains("大店长")){
            int conAll = performancePointMapper.ddzAllCon(account,time, null);//门店总数
            int con = performancePointMapper.ddzCon(account,time);//可做绩效门店数
            map.put("conAll", conAll);
            map.put("con", con);
        }

        if (ToolUtil.isEmpty(map)){
            map.put("conAll", 0);
            map.put("con", 0);
        }
        return ResponseData.success(map);
    }



    /**
     * 查询待提交，待审核，被驳回，已通过的门店数量及列表
     * @param account
     * @return
     */
    @Override
    public ResponseData tddgetShopSumState(String account, BtyPerformanceReceiveParam param) {
        Map<Object, Object> map = new HashMap<>();
        map.put("con", 0);
        map.put("list", new ArrayList<>());

        if (ToolUtil.isEmpty(param.getTime())){
            Map<String,String> mapTime = getPerformanceDay();
            param.setTime(mapTime.get("lastYearMonth"));
        }
        Page pageContext = getPageContext();
        //判断该用户在架构中，是否有，营运经理，督导，大店长，店长，职位
        String zwStr = attendAuditBtyAreaService.getBtyAreaZwByTel(account);

        String sta = param.getCheckStatus();//审核状态

        if (zwStr.contains("督导")){
            int con = performancePointMapper.ddAllCon(account, param.getTime(), sta);//门店总数
            IPage page = performancePointMapper.ddAllList(pageContext, account, param.getTime(), sta);//门店列表
            map.put("con", con);
            map.put("list", page.getRecords());
        }
        if (zwStr.contains("大店长")){
            int con = performancePointMapper.ddzAllCon(account, param.getTime(), sta);//门店总数
            IPage page = performancePointMapper.ddzAllList(pageContext, account, param.getTime(), sta);//门店列表
            map.put("con", con);
            map.put("list", page.getRecords());
        }

        return ResponseData.success(map);
    }

    private Serializable getKey(BtyPerformanceMonthCheckParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyPerformanceMonthCheck getOldEntity(BtyPerformanceMonthCheckParam param) {
        return this.getById(getKey(param));
    }

    private BtyPerformanceMonthCheck getEntity(BtyPerformanceMonthCheckParam param) {
        BtyPerformanceMonthCheck entity = new BtyPerformanceMonthCheck();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }




    /**
     * 19  运营经理提交驳回，原因，列表
     * @author wjk
     * @Date 2022-04-06
     */
    @Override
    public boolean tyyjlsetDismissedList(String account, List<BtyPerformanceMonthInformationResult> param) {

        // 判断运营经理有这个店的权限
        // 根据手机号，和妖码查询该店，若能查询到，则证明有这个
        BtyPerformanceReceiveParam btyPerformanceReceiveParam = new BtyPerformanceReceiveParam();
        btyPerformanceReceiveParam.setYaoma(param.get(0).getYaoma());
        LayuiPageInfo layuiPageInfo = this.btyPerformancePointService.tyyjlgetShopStateListPage( account, btyPerformanceReceiveParam);
        if(String.valueOf(layuiPageInfo.getCount()).equals("0")){
            return false;
        }

        BtyPerformanceMonthCheck btyPerformanceMonthCheck = this.getById(param.get(0).getBtyPerformanceMonthCheckId());
//        // 若状态是待提交，未审核
//        if(String.valueOf(btyPerformanceMonthCheck.getCheckStatus()).equals("1")){
            // 更新审核表的状态 (audit_status:1 to 2 ) 驳回
            Boolean flagChenk = this.baseMapper.updateRejectById(param.get(0).getBtyPerformanceMonthCheckId());


            // 增加驳回员工的驳回信息
            int size = addDismissedServiceList(account,param);

            return flagChenk;
//        }
//
//        return false;
    }

    /**
     * 20     运营经理提交总驳回原因
     * @author wjk
     * @Date 2022-04-06
     */
    @Override
    public boolean tyyjlSetDismissedTotal(String account, BtyPerformanceMonthInformationResult param) {
        // 根据手机号，和妖码查询该店，若能查询到，则证明有这个
        BtyPerformanceReceiveParam btyPerformanceReceiveParam = new BtyPerformanceReceiveParam();
        btyPerformanceReceiveParam.setYaoma(param.getYaoma());
        LayuiPageInfo layuiPageInfo = this.btyPerformancePointService.tyyjlgetShopStateListPage( account, btyPerformanceReceiveParam);
        if(String.valueOf(layuiPageInfo.getCount()).equals("0")){
            return false;
        }

        BtyPerformanceMonthCheck btyPerformanceMonthCheck = this.getById(param.getBtyPerformanceMonthCheckId());

        Boolean flagChenk = this.baseMapper.updateRejectById(param.getBtyPerformanceMonthCheckId());

        // 增加驳回的总原因
        int size = addDismissedServiceOne(account,param);

        return flagChenk;
    }



    /**
     * 21  运营经理批量通过按钮
     * @author wjk
     * @Date 2022-04-06
     */
    @Override
    public boolean tyyjlSetStateApproved(String account, List<BtyDdpageByAccountTime> param) {

        List<Long> btyPerformanceMonthCheckIdList = getCheckIdList(param);

        //更新审核表的状态 (audit_status:1 to 3 )
        int backFalg = this.baseMapper.setCheckAuditApproved(btyPerformanceMonthCheckIdList);
        boolean listFalg = false;
        if(backFalg > 0 ){
            listFalg = true;
        }
        return listFalg;
    }

    /**
     * 点击同步，同步该店，运营经理，督导的占比
     * @param account
     * @param yaoma
     * @return
     */
    @Override
    public ResponseData tddSynchronousYyjlAndDd(String account, String yaoma) {

        // 根据用户手机号，和店面的妖码，还有当前时间，验证当前用户是否有操作此店本月绩效的权限
        BtyPerformanceMonthPermissionsParam permissionsParam = new BtyPerformanceMonthPermissionsParam();
        permissionsParam.setAccount(account);
        permissionsParam.setYaoma(yaoma);

        Map<String,String> mapPermissions = this.BtyPerformanceMonthPermissionsValidation(permissionsParam);
        if(mapPermissions.get("permissionsValid").equals("false")){
            return ResponseData.error(403, mapPermissions.get("permissionsInfo"), false);
        }

        // 根据妖码和时间，查询这个店的信息
        Map<String,String> mapTime = getPerformanceDay();
        String time = mapTime.get("lastYearMonth");

        //根据妖码和时间，查询这个店的营运经理、督导
        List<BtyPerformanceMonthInformation> list = btyPerformanceMonthInformationMapper.getByYaoma(time, yaoma);
        //获取该店审核状态
        BtyPerformanceMonthCheck monthCheck = baseMapper.getByYm(time, yaoma);
        //创建及驳回状态才可同步
        if (ToolUtil.isNotEmpty(monthCheck) && (monthCheck.getCheckStatus() == 0 || monthCheck.getCheckStatus() == 2)){

            if (ToolUtil.isNotEmpty(list)){
                //查询bty_performance_month_information表中是否有该店数据
                List<BtyPerformanceMonthInformation> informations = btyPerformanceMonthInformationMapper.getByBh(time, yaoma, list);
                if (ToolUtil.isNotEmpty(informations)){
                    Map<String, BtyPerformanceMonthInformation> map = informations.stream().collect(Collectors.toMap(s -> s.getBh(), s -> s));

                    for (BtyPerformanceMonthInformation result : list) {
                        BtyPerformanceMonthInformation information = map.get(result.getBh());
                        //存在数据
                        if (ToolUtil.isNotEmpty(information)){
                            information.setRatio(result.getRatio());//占比
                            information.setUpdateTime(new Date());
                            information.setUpdateUser(Long.valueOf(account));
                            //修改
                            btyPerformanceMonthInformationMapper.updateByBh(information);
                        }else {
                            Long btyPerformanceMonthInformationId = UUIDUtils.getId();

                            result.setId(btyPerformanceMonthInformationId);
                            result.setBtyPerformanceMonthCheckId(monthCheck.getId());
                            result.setLastFlag(0);
                            result.setDelFlag(0);
                            result.setCreateTime(new Date());
                            result.setCreateUser(Long.valueOf(account));
                            //新增
                            btyPerformanceMonthInformationService.save(result);
                        }
                    }
                }else {
                    for (BtyPerformanceMonthInformation result : list){
                        Long btyPerformanceMonthInformationId = UUIDUtils.getId();
                        result.setId(btyPerformanceMonthInformationId);
                        result.setBtyPerformanceMonthCheckId(monthCheck.getId());
                        result.setLastFlag(0);
                        result.setDelFlag(0);
                        result.setCreateTime(new Date());
                        result.setCreateUser(Long.valueOf(account));
                    }
                    //新增
                    this.btyPerformanceMonthInformationService.saveList(list);
                }
            }

        }else {
            return ResponseData.error(403, "该店绩效已操作，不可同步！",false);
        }

        return ResponseData.success();
    }

    private List<Long> getCheckIdList(List<BtyDdpageByAccountTime> param) {
        ArrayList<Long> checkIdList = new ArrayList<Long>();
        param.forEach(attendAuditManagerSetResult ->{
            checkIdList.add(attendAuditManagerSetResult.getBtyPerformanceMonthCheckId());
        });
        //System.out.println(aaIdList);
        List<Long> aaIdListWithoutDuplicates = checkIdList.stream().distinct().collect(Collectors.toList());
        //System.out.println(aaIdListWithoutDuplicates);
        return aaIdListWithoutDuplicates;
    }

    /**
     *  增加驳回的总原因
     * @param account
     * @param param
     * @return
     */
    private int addDismissedServiceOne(String account, BtyPerformanceMonthInformationResult param) {

        //判断该用户是否已经在人事表中有数据
        AttendAuditBtyArchives yyjlArchives = attendAuditBtyArchivesService.getOneByPhone(account);
        param.setBtyPerformanceMonthInformationId(param.getId());
        Long id = UUIDUtils.getId();
        param.setId(id);
        param.setYySupervisorBh(yyjlArchives.getBh());
        param.setYySupervisorPhone(account);
        param.setYySupervisorName(yyjlArchives.getXm());

        int  size = this.baseMapper.addDismissedServiceOne(param);
        return size;
    }

    /**
     * 运营经理添加驳回
     *
     * @param account
     * @param param
     * @return
     */
    private int addDismissedServiceList(String account, List<BtyPerformanceMonthInformationResult> param) {

        //判断该用户是否已经在人事表中有数据
        AttendAuditBtyArchives yyjlArchives = attendAuditBtyArchivesService.getOneByPhone(account);

        List<BtyPerformanceMonthInformationResult>  dismissedList = new ArrayList<BtyPerformanceMonthInformationResult>();

        for(BtyPerformanceMonthInformationResult result : param){
            //确定驳回信息是有数据的
            if(ToolUtil.isNotEmpty(result.getDismissedNote())){
                result.setBtyPerformanceMonthInformationId(result.getId());
                Long id = UUIDUtils.getId();
                result.setId(id);
                result.setYySupervisorBh(yyjlArchives.getBh());
                result.setYySupervisorPhone(account);
                result.setYySupervisorName(yyjlArchives.getXm());
                dismissedList.add(result);
            }
        }
        int size = 0;
        if(dismissedList.size()>0){
            //批量增加驳回信息
            size = this.baseMapper.addDismissedList(dismissedList);
        }

        return size;


    }


}
